package edu.gyc.producer.consumer;

import java.util.ArrayList;
import java.util.List;

class Mask{
    private int id;
    private String type;

    public Mask(int id, String type) {
        this.id = id;
        this.type = type;
    }

    @Override
    public String toString() {
        return "Mask{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}

public class MaskFactory {
    private Integer stockNum=0;
    private static int maskid=0;
    private List<Mask> masks = new ArrayList<>();
    public synchronized void put() {
        while (stockNum>=10){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        maskid++;
        Mask mask=new Mask(maskid,"N95");
        masks.add(mask);
        stockNum++;
    System.out.println(Thread.currentThread().getName()+"生产口罩 "+mask+" 库存 "+stockNum);
        notify();
    }
    public synchronized void get() {
        while (stockNum<=0){
            try {
               // wait();
                wait(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       Mask mask= masks.remove(0);
        stockNum--;
        System.out.println(Thread.currentThread().getName()+"获得口罩 "+mask+" 库存 "+stockNum);


        notify();
    }

    public static void main(String[] args) {
        MaskFactory maskFactory=new MaskFactory();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {

                maskFactory.put();
            }
        },"生产者1").start();
        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                maskFactory.put();
            }
        },"生产者2").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                maskFactory.get();
            }
        },"消费者1").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                maskFactory.get();
            }
        },"消费者2").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                maskFactory.get();
            }
        },"消费者3").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                maskFactory.get();
            }
        },"消费者4").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                maskFactory.get();
            }
        },"消费者5").start();
    }
}
